package oop.ex3.common;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketCommunicationSession implements CommunicationSession {
	private static final int SOCKET_TIMEOUT = 5 * 1000;
	private Socket _socket;
	private DataInputStream _inputStream;
	private DataOutputStream _outputStream;

	public SocketCommunicationSession(String host, int port) throws IOException {
		_socket = new Socket(host, port);
		//_socket.setSoTimeout(SOCKET_TIMEOUT);
		_inputStream = new DataInputStream(_socket.getInputStream());
		_outputStream = new DataOutputStream(_socket.getOutputStream());
	}

	public SocketCommunicationSession(Socket socket) throws IOException {
		_socket = socket;
		//		_socket.setSoTimeout(SOCKET_TIMEOUT);
		_inputStream = new DataInputStream(_socket.getInputStream());
		_outputStream = new DataOutputStream(_socket.getOutputStream());
	}

	@Override
	public void close() throws IOException {
		_inputStream.close();
		_outputStream.close();
		_socket.close();
	}

	@Override
	public void sendString(String input) throws IOException {
		_outputStream.writeUTF(input);
		_outputStream.flush();
	}

	@Override
	public void sendInt(int input) throws IOException {
		_outputStream.writeInt(input);
		_outputStream.flush();
	}

	@Override
	public String readString() throws IOException {
		return _inputStream.readUTF();
	}

	@Override
	public int readInt() throws IOException {
		return _inputStream.readInt();
	}

	@Override
	public byte[] readByteArray() throws IOException {
		long fileSize = _inputStream.readLong();
		byte[] result = new byte[(int) fileSize];
		for (int index = 0; index < fileSize; index++) {
			byte currentByte = _inputStream.readByte();
			result[index] = currentByte;
		}
		return result;
	}

	public void writeByteArray(File file) throws IOException {
		//sending the file's size:
		long fileSize = file.length();
		_outputStream.writeLong(fileSize);
		FileInputStream fileInputStream = new FileInputStream(file);
		for(int index = 0; index < fileSize; index++){
			_outputStream.write(fileInputStream.read());
		}
		
		
		
		

	}
}